<?php

namespace Common\Model;

use Think\Model;

class AnswerModel extends Model
{
    /**
     * 获取回答列表
     * @param array        $map  条件
     * @param bool         $page 是否分页
     * @param array|string $sort 排序方式
     * @param int          $num  限制获取条数
     * @return array
     */
    public function get_list($map = array(), $page = false, $sort = '', $num = 10, $startrow='')
    {
        $limit = $num ? $num : 10;

        if (empty($sort)) {
            $sort = 'id DESC';
        }
        if ($page) {
            $count    = $this->where($map)->count();
            $Page     = pager($count, $limit);
            $limit    = $Page->firstRow . ',' . $Page->listRows;
            $page_str = $Page->fshow();
            $list = $this->where($map)->order($sort)->limit($limit)->select();
        } else {
            $list = $this->where($map)->order($sort)->limit($startrow . ',' . $limit)->select();
        }


        $list = array_map(array($this, 'fill'), $list);

        $return['list']  = $list;
        $return['count'] = $page ? $count : count($list);
        $return['page']  = $page_str;

        return $return;
    }

    /**
     * 问题填充字段
     * @param array $v 记录数组
     * @return array
     */
    public function fill($v)
    {
		if (empty($v)){
		return false;
		}
        $v['question']    = D('Question')->get_question_one($v['qid']);
        $v['content_str'] = $v['content'];
        $v['content_cut'] = cut_str($v['content'], 100);
        $v['content']     = ytata_strip_tags($v['content']);
        $v['user']        = D('User')->get_user_one($v['uid'], true, 1);
        $v['addtime_str'] = daterange($v['addtime']);
        $v['asked']       = D('AnswerReply')->get_answer_reply($v['id']);

        return $v;
    }

    /**
     * 获取单条回答
     * @param string $qid
     * @param string $uid
     * @return mixed
     */
    public function get_answer_one($qid = '', $uid = '', $fill = false)
    {
        if (!empty($qid)) {
            $map['qid'] = intval($qid);
        }
        if (!empty($uid)) {
            $map['uid'] = intval($uid);
        }

        $info = $this->where($map)->find();

        if (!empty($info)) {
            $info['addtime_str'] = daterange($info['addtime']);
        }

        // 填充字段
        if ($fill === true) {
            $info = array_merge($info, $this->fill($info));
        }

        return $info;
    }

    /**
     * 删除回答
     * @param array|int $ids
     * @return int
     */
    public function del_answer($ids,$uid='')
    {
        $ids = is_array($ids) ? implode(",", $ids) : $ids;

        if (empty($ids)) {
            $ret['status']  = false;
            $ret['content'] = 'ID不能为空';
            return $ret;
        }
        if (!is_match_ids($ids)) {
            $ret['status']  = false;
            $ret['content'] = '参数错误';
            return $ret;
        }

        $count = 0;
        $answerlist  = M('Answer')->select($ids);
        if (!empty($answerlist)) {
            $qids  = array_column($answerlist, 'qid');
			if (!empty($uid)){
			$map['uid']=intval($uid);
			}
            $count = M("Answer")->where($map)->delete($ids);
            $this->on_answer_del($answerlist);
        }

        $ret['status']  = true;
        $ret['content'] = '删除成功';
        $ret['count']   = (int)$count;

        return $ret;
    }

    /**
     * 删除问题回答相关处理
     *
     * @param array $answerlist
     */
    protected function on_answer_del($answerlist)
    {
        $qids = array_column($answerlist, 'qid');

        D('Question')->edit_answercount($qids);  // 修改问题回答总数
    }

    /**
     * 获取单条回答
     * @param string $id
     * @return mixed
     */
    public function get_answer_one_id($id = '')
    {
        $map['id'] = intval($id);
        $list      = $this->where($map)->find();

        return $list;
    }

    // 点赞
    public function praise($uid, $aid)
    {
        if (empty($uid) || empty($aid)) {
            $this->ajaxReturn(0, "参数错误");
        }

        $praise = M('AnswerPraise')->where(compact('uid', 'aid'))->find();
        if ($praise) {
            $res['status'] = 2;
            $res['msg'] = '已点过赞';
            return $res;
        }
        $ret = D('AnswerPraise')->praise_add($uid, $aid);
        // 点赞失败
        if (!$ret['status']) {
            $res['status'] = 0;
            $res['msg'] = $ret['msg'];
            return $res;
        }

        $res['status'] = 1;
        $res['msg'] = $ret['msg'];
        $answer = $this->field('praise')->find($aid);
        $res['count_praise'] = $answer['praise'];
        return $res;
    }

    /**
     * 更新点赞 点赞数+1
     * @param int $rid 回答ID
     * @return bool
     */
    public function inc_praise($rid = null)
    {
        $map['id'] = intval($rid);
        $this->where($map)->setInc('praise', 1);
        return true;
    }

    /**
     * 获取点赞数量
     * @param string $rid 回答ID
     * @return int
     */
    public function get_praise($rid = '')
    {
        $map['id'] = intval($rid);
        $praise    = $this->field('praise')->where($map)->find();

        return (int)$praise['praise'];
    }

    /**
     * 获取浏览总数（帮助过的人）
     * @param string $uid
     * @return int
     */
    public function get_click_total($uid = '')
    {
        $map['uid'] = intval($uid);

        $click = $this->where($map)->sum('click') ?: 0;

        return $click;
    }

    /**
     * 设为最佳答案
     * @param string $rid
     * @return bool
     */
    public function set_optimal($rid = '')
    {
        $map['id']      = intval($rid);
        $map['optimal'] = 1;
        M('Answer')->save($map);

        return true;
    }

    /**
     * 统计回答数量（全部/已采纳）
     * @param string $uid
     * @param string $optimal
     * @param string $qid
     * @return int
     */
    public function count_answer($uid = '', $optimal = '', $qid = '')
    {
        if (!empty($uid)) {
            $map['uid'] = intval($uid);
        }
        if (!empty($qid)) {
            $map['qid'] = intval($qid);
        }
        if (!empty($optimal)) {
            $map['optimal'] = intval($optimal);
        }

        $count = $this->where($map)->count();

        return $count;
    }

    /**
     * 计算采纳率（已采纳/回答总数）
     * @param string $uid
     * @return float
     */
    public function acc_rate($uid = '')
    {
        $map['uid']     = intval($uid);
        $count          = $this->where($map)->count();
        $map['optimal'] = 1;
        $count1         = $this->where($map)->count();
        $rate           = round(($count1 / $count) * 100);

        return $rate;
    }

    /**
     * 修改点击次数
     * 指定问题ID的全部回答访问数+1
     * @param string $id 回答所属问题的ID
     * @return bool
     */
    public function edit_click($id = '')
    {
        $map['qid'] = intval($id);
        $this->where($map)->setInc('click', 1);
        return true;
    }

    // 添加回答
    public function answer_add($uid, $qid, $data)
    {
        $ban = D('UserBan')->chenk_ban($uid);
        if (!empty($ban)) {
            $ret['status'] = false;
            $ret['msg']    = "发表失败，您已经被禁言（{$ban['txt']}），禁言结束时间：{$ban['endtime_str']}";
            return $ret;
        }

        $q_info = D('Question')->get_question_one($qid);
        if (empty($q_info)) {
            $ret['status'] = false;
            $ret['msg']    = "问题不存在！";
            return $ret;
        }

        if ($q_info['uid'] == $uid) {
            $ret['status'] = false;
            $ret['msg']    = "不能回答自己的提问！";
            return $ret;
        }

        $reply = D('Answer');
        $info  = $reply->get_answer_one($qid, $uid);
        if (!empty($info))//如果没有回答过
        {
            $ret['status'] = false;
            $ret['msg']    = "不能重复回答！";
            return $ret;
        }

        if (!isset($data['content']) || empty($data['content'])) {
            $ret['status'] = false;
            $ret['msg']    = "请填写内容！";
            return $ret;
        }

        $map['uid']     = $uid;
        $map['qid']     = $qid;
        $map['content'] = $data['content'];
        $map['addtime'] = isset($data['addtime']) ? $data['addtime'] : time();
        if (!$reply->create($map)) {
            $ret['status'] = true;
            $ret['msg']    = $reply->getError();
            return $ret;
        }

        $aid = $reply->add();
        D('Question')->edit_answercount($qid);//更新问题回答总数
        D('Question')->edit_answeruid($qid, $uid, $data['addtime']);//更新问题的最后回复人
        D('User')->edit_answercount($uid);//更新会员回答总数
        D('UserTrack')->add_track($uid, $qid, 2, $aid);//写入个人动态
        D('Task')->exe_reply_question($uid);//完成回答问题任务
        //短信通知
        $question = D('Question')->get_question_one($qid);
        $user     = D('User')->get_user_one($question['uid']);
        $SMSopen  = C('YTATA_SMS_OPEN');
        if ($SMSopen && $question['sms_remind'] == '1' && !empty($user['mobile'])) {
            $params['sitename'] = C('YTATA_SITE_NAME');
            $send               = send_sms($user['mobile'], $params, 'answer_remind');
        }
        D('WeixinMsgtpl')->send_userreplymsg($uid, $qid, $data['content'], 'question'); // 微信模板消息通知
        D('Rank')->add_record('answer', $uid, 1);  // 记录排行数据 用于排行计算

        $ret['status'] = true;
        $ret['msg']    = '';
        $ret['aid']    = $aid;

        return $ret;
    }

    // 回答被采纳
    public function answer_adoption($uid, $qid, $aid)
    {
        $question = D('Question')->get_question_one($qid, $uid);
        if (empty($question)) {
            $ret['status'] = false;
            $ret['msg']    = "数据错误！" . $qid . '+' . $uid;
            return $ret;
        } else { //结算积分
            if ($question['issolve'] == '1') {
                $ret['status'] = false;
                $ret['msg']    = "已采纳答案";
                return $ret;
            }

            $answer = D('Answer')->get_answer_one_id($aid);
            $t      = D('Task');
            $t->exe_reply_adoption($answer['uid']);//采纳答案，答题人获得系统奖励
            if ($question['reward'] > 0)//假如有悬赏，奖励派发给回答人
            {
                D('User')->edit_user_gold(1, $answer['uid'], $question['reward'], '答案被采纳获得提问者悬赏奖励');
            }
            $t->exe_adoption_answer($uid);//采纳答案，提问人(自己)获得系统奖励
            D('Question')->set_solve($qid);//更新问题状态（改为解决状态）
            D('Answer')->set_optimal($aid);//更新回复状态（改为最佳答案）
            D('User')->update_acc_rate($answer['uid']);//更新采纳率
            D('UserTrack')->add_track($uid, $qid, 9, $aid);//写入个人动态
            D('Rank')->add_record('optimal', $answer['uid'], 1);  // 排行采纳数据记录

            $ret['status'] = true;
            $ret['msg']    = '';
            return $ret;
        }
    }
}